<?php

if (!defined('SYSPATH')) exit("No direct script access allowed!");

class CL_AppEngine {

    private static $instance = NULL;

    private $config;
    private $router;
    private $uri;
    private $appName = '';

    private function CL_AppEngine() {

        $this->uri = CL_URI::get_instance();

        // set_name() defiens constant APPNAME hence needs to be called before
        // loading any app handling libraries
        $this->set_name();
        
        $this->router = CL_Router::get_instance();
        $this->config = CL_Config::get_instance();
    }

    /**
     * @return CL_AppEngine
     */
    public static function get_instance() {
        if (self::$instance === NULL) {
            self::$instance = new CL_AppEngine();
        }
        return self::$instance;
    }

    private function set_name() {

        if (!isset($this->uri->segments[0]) || $this->uri->segments[0] != 'app') {
            show_error("Application appears to be called from wrong location.", "Application Router Error");
        }

        if (count($this->uri->segments) > 1) {
            $this->appName = $this->uri->segments[1];
        }

        define('APPNAME', $this->appName);
    }

    public function run() {

        $class = $this->router->app_fetch_class();
        $method = $this->router->app_fetch_method();
        $app = APPNAME;

        if (!app_controller_exists(APPNAME, $class)) {
            show_error("Application controller '$class' does not exist for '$app' application.", "AppEngine Error");
        }

        require_once APPSPATH . APPNAME . '/controllers/' . $class . '.php';

        if (!controller_is_callable($class, $method)) {
            show_error("Requested controller '$class/$method' is not callable for '$app' application. Does the method '$method' exist?", "AppEngine Error");
        }

        $controller = new $class();

        call_user_func(array($controller, $method));
        call_end_method($controller);
    }
}

/* End of file AppEngine.php */
/* Location: /system/libraries/AppEngine.php */